package com.zhangzhan.gulimallorder.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhangzhan.gulimallcommcon.enums.OrderStatusEnum;
import com.zhangzhan.gulimallcommcon.tos.SeckillCreateTo;
import com.zhangzhan.gulimallcommcon.util.PageUtils;
import com.zhangzhan.gulimallcommcon.util.Query;
import com.zhangzhan.gulimallorder.config.AlipayTemplate;
import com.zhangzhan.gulimallorder.dao.OrderDao;
import com.zhangzhan.gulimallorder.dao.OrderItemDao;
import com.zhangzhan.gulimallorder.entity.OrderEntity;
import com.zhangzhan.gulimallorder.entity.OrderItemEntity;
import com.zhangzhan.gulimallorder.entity.PaymentInfoEntity;
import com.zhangzhan.gulimallorder.service.OrderService;
import com.zhangzhan.gulimallorder.service.PaymentInfoService;
import com.zhangzhan.gulimallorder.vos.PayAsyncVo;
import com.zhangzhan.gulimallorder.vos.PayVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    private OrderItemDao orderItemDao;

    @Autowired
    private AlipayTemplate alipayTemplate;

    @Autowired
    private PaymentInfoService paymentInfoService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderEntity getByOrderSn(String orderSn) {

        return this.getOne(Wrappers.<OrderEntity>lambdaQuery()
                .eq(OrderEntity::getOrderSn, orderSn));
    }

    @Override
    public String alipay(String orderSn) throws AlipayApiException {

        OrderEntity order = this.getOne(Wrappers.<OrderEntity>lambdaQuery()
                .eq(OrderEntity::getOrderSn, orderSn));

        List<OrderItemEntity> entityList = orderItemDao.selectList(Wrappers.<OrderItemEntity>lambdaQuery()
                .eq(OrderItemEntity::getOrderSn, orderSn));

        PayVo payVo = new PayVo();
        payVo.setOut_trade_no(orderSn);
        payVo.setSubject(entityList.get(0).getSpuName());
        payVo.setTotal_amount(order.getPayAmount().setScale(2, RoundingMode.UP).toString());
        payVo.setBody(entityList.get(0).getSpuName());

        String html = alipayTemplate.pay(payVo);

        return html;
    }

    @Override
    public String alipayed(PayAsyncVo payAsyncVo) {
        //支付信息表
        PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
        paymentInfoEntity.setOrderSn(payAsyncVo.getOut_trade_no());
        paymentInfoEntity.setAlipayTradeNo(payAsyncVo.getTrade_no());
        paymentInfoEntity.setTotalAmount(new BigDecimal(payAsyncVo.getTotal_amount()));
        paymentInfoEntity.setSubject(payAsyncVo.getSubject());
        paymentInfoEntity.setPaymentStatus(payAsyncVo.getTrade_status());
        paymentInfoEntity.setCreateTime(new Date());
        paymentInfoEntity.setConfirmTime(payAsyncVo.getGmt_create());
        paymentInfoEntity.setCallbackTime(payAsyncVo.getNotify_time());
        paymentInfoEntity.setCallbackContent(JSON.toJSONString(payAsyncVo));
        paymentInfoService.save(paymentInfoEntity);

        //判断支付状态
        if ("TRADE_SUCCESS".equals(payAsyncVo.getTrade_status()) || "TRADE_FINISHED".equals(payAsyncVo.getTrade_status())) {
            //	支付成功
            OrderEntity orderEntity = new OrderEntity();
            orderEntity.setStatus(OrderStatusEnum.PAYED.getCode());
            this.update(orderEntity, Wrappers.<OrderEntity>lambdaUpdate()
                    .eq(OrderEntity::getOrderSn, payAsyncVo.getOut_trade_no()));
        }
        return "success";
    }

    @Override
    @Transactional
    public String seckillCreate(SeckillCreateTo seckillCreateTo) {
        if (Objects.nonNull(seckillCreateTo)){
            OrderEntity orderEntity = new OrderEntity();
            orderEntity.setOrderSn(seckillCreateTo.getOrderSn());
            orderEntity.setMemberId(seckillCreateTo.getMemberTo().getId());
            orderEntity.setMemberUsername(seckillCreateTo.getMemberTo().getUsername());
            orderEntity.setPayAmount(seckillCreateTo.getSeckillPrice());
            orderEntity.setStatus(0);

            this.save(orderEntity);

            OrderItemEntity orderItemEntity = new OrderItemEntity();
            orderItemEntity.setOrderSn(seckillCreateTo.getOrderSn());
            orderItemEntity.setSkuId(seckillCreateTo.getSkuId());
            orderItemEntity.setSkuQuantity(seckillCreateTo.getNum());
            orderItemEntity.setSkuPrice(seckillCreateTo.getSeckillPrice());

            orderItemDao.insert(orderItemEntity);
            return "success";
        }

        return null;
    }

}